package com.huang.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.huang.enums.CommonCodeEnum;
import com.huang.resp.CommonResult;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;

/**
 * @author han
 * @since 2022-01-12 20:21:06
 */
@Configuration
public class SentinelConfig {

    /**
     * 自定义异常
     */
    @PostConstruct
    public void initBlockHandlerException() {
        BlockRequestHandler blockRequestHandler = (exchange, t) ->
                ServerResponse.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(CommonResult.error(CommonCodeEnum.FLOW_LIMIT_ERROR)));
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

}
